package com.virtium.vpc.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Provides Hibernate utility methods that can be used to perform common operations.
 * 
 * @author TuanAnh
 *
 */
public class HibernateUtil {

	private static Log log = LogFactory.getLog(HibernateUtil.class);
	
    private static final SessionFactory sessionFactory;
    
    public Object clone()
	throws CloneNotSupportedException {
    	throw new CloneNotSupportedException(); 
    	// that'll teach 'em
	}
    
    //Create the initial SessionFactory from the default configuration files
    static {
        try {
	        log.info("Building Hibernate Session Factory...");
	        
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
            
        } catch (Throwable ex) {
	        
            // Make sure you log the exception, as it might be swallowed
            log.error("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
            
        }      
    }
 
	public static Session openSession()
	throws HibernateException {
		log.debug("**** Opening Hibernate Session ****");		
		Session s = sessionFactory.openSession();    	 		
		return s;
	}
    
	public void closeFactorySession()
	throws HibernateException {
		log.debug("**** Closing Hibernate Session Factory ****");
		sessionFactory.close();
	}

}


